/*
 * Copyright 2014 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.alibaba.wallstreet.uitls;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.alibaba.wallstreet.service.util.ReflectUtil;

/**
 * Bean 属性赋值的工具类
 * 
 * @author moxian.zl 2014-2-12 下午3:36:38
 */
public class BeanUtil extends BeanUtils {

    /**
     * 该方法进行了扩展<br>
     * 1、支持 Long vs Date<br>
     * 2、支持 Enum vs String
     */
    public static void copyProperties(Object source, Object target) {
        ReflectUtil.beanCopy(source, target);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void trim(Object o) {
        if (o == null || ClassUtil.isPrimitiveClass(o.getClass()) || o.getClass() == String.class) {
            return;
        }
        if (o instanceof List) {
            List list = (List) o;
            for (int i = 0; i < list.size(); i++) {
                Object item = list.get(i);
                if (item instanceof String) {
                    String strItem = (String) item;
                    list.set(i, strItem.trim());
                } else {
                    trim(item);
                }
            }
        } else if (o instanceof Map) {
            Map map = (Map) o;
            for (Object key : map.keySet()) {
                Object item = map.get(key);
                if (item instanceof String) {
                    String strItem = (String) item;
                    map.put(key, strItem.trim());
                } else {
                    trim(item);
                }
            }
        } else {
            BeanWrapper beanWrapper = new BeanWrapperImpl(o);
            Field[] fields = o.getClass().getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                if (!beanWrapper.isReadableProperty(fieldName)) {
                    continue;
                }
                Object value = beanWrapper.getPropertyValue(fieldName);
                if (value instanceof String) {
                    if (beanWrapper.isWritableProperty(fieldName)) {
                        String strValue = (String) value;
                        beanWrapper.setPropertyValue(field.getName(), strValue.trim());
                    }
                } else {
                    trim(value);
                }
            }
        }
    }
}
